package com.lanou.horo.zhuizhui.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.lanou.horo.zhuizhui.R;
import com.lanou.horo.zhuizhui.entity.greendao.User_Message;
import com.lanou.horo.zhuizhui.utility.customDialog.CustomProgressDialog;
import com.lanou.horo.zhuizhui.entity.greendao.UserMsgDaoHelper;
import com.lanou.horo.zhuizhui.utility.customImage.RoundedImageView;
import com.lanou.horo.zhuizhui.utility.imageLoader.BaseApplication;
import com.lanou.horo.zhuizhui.utility.imageLoader.VolleySingleton;

import java.io.ByteArrayOutputStream;


/**
 * Created by dllo on 15/11/9.
 */
public class UserInformationActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView userCancelBtn, userSaveBtn;
    private Button outOfuserBtn;
    private RoundedImageView userPersnloPhoto;
    private EditText userNickNameET, userSignatureET;
    private UserMsgDaoHelper helper;
    private Bitmap bitmap, backBitmap;
    private ContentResolver cr;
    private NetworkImageView userBackgroundImg;
    private ImageLoader imageLoader;
    private CustomProgressDialog dialog;
//    ///////////////
//    private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
//    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
//    private static final int PHOTO_REQUEST_CUT = 3;// 结果
//    private File tempFile = new File(Environment.getExternalStorageDirectory(),
//            getPhotoFileName());


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_information_user);
        init();
    }

    private void init() {
        dialog = new CustomProgressDialog(this, "加载中...", R.anim.loding);
        dialog.setCanceledOnTouchOutside(false);
        imageLoader = VolleySingleton.getInstance().getImageLoader();
        userBackgroundImg = (NetworkImageView) findViewById(R.id.userBackgroundImg);
        userBackgroundImg.setOnClickListener(this);
        userPersnloPhoto = (RoundedImageView) findViewById(R.id.userPersnloPhoto);
        userPersnloPhoto.setOnClickListener(this);
        userCancelBtn = (TextView) findViewById(R.id.userCancelBtn);
        userCancelBtn.setOnClickListener(this);
        outOfuserBtn = (Button) findViewById(R.id.outOfuserBtn);
        outOfuserBtn.setOnClickListener(this);
        userSaveBtn = (TextView) findViewById(R.id.userSaveBtn);
        userSaveBtn.setOnClickListener(this);
        userNickNameET = (EditText) findViewById(R.id.userNickNameET);
        userSignatureET = (EditText) findViewById(R.id.userSignatureET);
        helper = UserMsgDaoHelper.getInstance();
        userNickNameET.setText(BaseApplication.getUser().getName());
        userSignatureET.setText(BaseApplication.getUser().getSignature());

        cr = this.getContentResolver();


        Intent intent = this.getIntent();
        if (intent != null && intent.getStringExtra("image") != null) {
            userBackgroundImg.setImageUrl(intent.getStringExtra("image"), imageLoader);
        }

        if (BaseApplication.getUser().getUserPhoto()!= null){
            userPersnloPhoto.setImageBitmap(BytesToBimap(BaseApplication.getUser().getUserPhoto()));
        }

        if (BaseApplication.getUser().getUserBackground() != null){
        BitmapDrawable bd = new BitmapDrawable(getResources(), BytesToBimap(BaseApplication.getUser().getUserBackground()));
        userBackgroundImg.setBackground(bd);

        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.userCancelBtn:
                finish();
                break;
            case R.id.userSaveBtn:
                if (!userNickNameET.getText().toString().equals("")) {
                    String userName = userNickNameET.getText().toString();
                    String signature = userSignatureET.getText().toString();
                    userPersnloPhoto.setDrawingCacheEnabled(true);
                    if (userPersnloPhoto.getDrawingCache() != null) {
                        bitmap = Bitmap.createBitmap(userPersnloPhoto.getDrawingCache());
                    }
                    userPersnloPhoto.setDrawingCacheEnabled(false);
                    userBackgroundImg.setDrawingCacheEnabled(true);
                    if (userBackgroundImg.getDrawingCache() != null) {
                        backBitmap = Bitmap.createBitmap(userBackgroundImg.getDrawingCache());
                    }
                    userBackgroundImg.setDrawingCacheEnabled(false);
                    User_Message user_message = helper.updateByName(BaseApplication.getUser().getName());
                    if (bitmap != null) {
                        user_message.setUserPhoto(BitmapToBytes(bitmap));
                    }
                    if (backBitmap != null) {
                        user_message.setUserBackground(BitmapToBytes(backBitmap));
                    }
                    user_message.setName(userName);
                    user_message.setSignature(signature);
                    helper.update(user_message);

                    finish();
                } else {
                    Toast.makeText(this, "昵称不能为空", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.userPersnloPhoto:
//                Intent intent = new Intent();
//                intent.setClass(this,ClipPictureActivity.class);
//                startActivityForResult(intent, 0);
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_PICK);
                intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 0);
//
//                AlertDialog.Builder builder = new AlertDialog.Builder(this);
//                builder.setPositiveButton("图库", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                //相册
//                                Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
//                                getAlbum.setType("image/*");
//                                startActivityForResult(getAlbum, PHOTO_REQUEST_GALLERY);
//                            }}).setNegativeButton("相机", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                // 拍照
//                                Intent cameraintent = new Intent(
//                                        MediaStore.ACTION_IMAGE_CAPTURE);
//                                // 指定调用相机拍照后照片的储存路径
//                                cameraintent.putExtra(MediaStore.EXTRA_OUTPUT,
//                                        Uri.fromFile(tempFile));
//                                startActivityForResult(cameraintent,
//                                        PHOTO_REQUEST_TAKEPHOTO);}}).create().show();
                break;
            case R.id.outOfuserBtn:
                BaseApplication.setIslogin(false);
                finish();
                break;
            case R.id.userBackgroundImg:
                Intent imgintent = new Intent();
                imgintent.setClass(this, BackgroundActivity.class);
                startActivity(imgintent);
                finish();
                break;
        }
    }

    public byte[] BitmapToBytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {
        // 取 drawable 的长宽
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();
        // 取 drawable 的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        // 建立对应 bitmap
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        // 建立对应 bitmap 的画布
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        // 把 drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //返回数据正确与否判断
        if (data != null && requestCode == 0) {
            Uri uri = data.getData();
            //查询图片
            Cursor cursor = cr.query(uri, null, null, null, null);
            if (cursor != null) {
                //遍历cursor对象
                while (cursor.moveToNext()) {
                    //获取图片所对应的文件路径
                    String filePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    //解析路径图片并显示
                    Bitmap bm = BitmapFactory.decodeFile(filePath);
                    userPersnloPhoto.setImageBitmap(bm);
                }
                cursor.close();
            }
        }
    }

    public Bitmap BytesToBimap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }

//    public Bitmap returnBitMap(String url) {
//        URL myFileURL;
//        Bitmap bitmap = null;
//        try {
//            myFileURL = new URL(url);
//            //获得连接
//            HttpURLConnection conn = (HttpURLConnection) myFileURL.openConnection();
//            //设置超时时间为6000毫秒，conn.setConnectionTiem(0);表示没有时间限制
//            conn.setConnectTimeout(6000);
//            //连接设置获得数据流
//            conn.setDoInput(true);
//            //不使用缓存
//            conn.setUseCaches(false);
//            //这句可有可无，没有影响
//            conn.connect();
//            //得到数据流
//            InputStream is = conn.getInputStream();
//            //解析得到图片
//            bitmap = BitmapFactory.decodeStream(is);
//            //关闭数据流
//            is.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return bitmap;
//    }

//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        switch (requestCode) {
//            case PHOTO_REQUEST_TAKEPHOTO:// 当选择拍照时调用
//                startPhotoZoom(Uri.fromFile(tempFile));
//                break;
//            case PHOTO_REQUEST_GALLERY:// 当选择从本地获取图片时
//                // 做非空判断，当我们觉得不满意想重新剪裁的时候便不会报异常，下同
//                if (data != null) {
//                    startPhotoZoom(data.getData());
//                } else {
//                }
//                break;
//            case PHOTO_REQUEST_CUT:// 返回的结果
//                if (data != null)
//                    // setPicToView(data);
//                    userPersnloPhoto.setImageBitmap(decodeUriAsBitmap(data.getData()));
//                    //sentPicToNext(data);
//                    break;
//        }
//        super.onActivityResult(requestCode, resultCode, data);
//    }
//
////    private void sentPicToNext(Intent data) {
////
////            Uri uri = data.getData();
////            try {
////                if (this.getContentResolver().openInputStream(uri) != null){
////                Bitmap aabitmap = BitmapFactory.decodeStream(this.getContentResolver().openInputStream(uri));
////                    if (aabitmap != null)
////                userPersnloPhoto.setImageBitmap(aabitmap);
////                }
////            } catch (FileNotFoundException e) {
////                e.printStackTrace();
////            }
////        }
//
//    private Bitmap decodeUriAsBitmap(Uri uri) {
//        Bitmap bitmap = null;
//        try {
//            bitmap = BitmapFactory.decodeStream(getContentResolver()
//                    .openInputStream(uri));
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//            return null;
//        }
//        return bitmap;
//    }
//
//
//    private String getPhotoFileName() {
//        Date date = new Date(System.currentTimeMillis());
//        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
//        return dateFormat.format(date) + ".jpg";
//    }
//
//    //裁剪
//    private void startPhotoZoom(Uri uri) {
//        Intent intent = new Intent("com.android.camera.action.CROP");
//        intent.setDataAndType(uri, "image/*");
//        // crop为true是设置在开启的intent中设置显示的view可以剪裁
//        intent.putExtra("crop", "true");
//
//        // aspectX aspectY 是宽高的比例
//        intent.putExtra("aspectX", 1);
//        intent.putExtra("aspectY", 1);
//
//        // outputX,outputY 是剪裁图片的宽高
//        intent.putExtra("outputX", 300);
//        intent.putExtra("outputY", 300);
//        intent.putExtra("return-data", true);
//        intent.putExtra("noFaceDetection", true);
//        System.out.println("22================");
//        startActivityForResult(intent, PHOTO_REQUEST_CUT);
//    }
}
